<?php

namespace App\Service\Third;

use App\Model\GuildManage\GuildWithdrawal;
use App\Service\BaseService;
use WGCYunPay\Config;
use WGCYunPay\Service\Des3Service;
use App\Model\Withdraw;
// use WGCYunPay\Util\RsaUtil;

/**
 * 云账户下单回调
 */
class YunZhCallbackService extends BaseService
{
    public function handle()
    {
        $notifyData = $this->request->all();
        $config = $this->createConfig();
        $dataInfo = Des3Service::decode($notifyData['data'], $config->des3_key);
        // $result = new RsaUtil($config);
        // $verifyResult = $result->verify($notifyData);
        $orderId = $dataInfo['data']['order_id'] ?? '';
        if (!$orderId) return;
        log_info('提现回调'.json_encode($dataInfo));
        $updaInfo = [];
        if (isset($dataInfo['data']['status_detail']) && $dataInfo['data']['status_detail'] == 0) {
            $updaInfo['status'] = Withdraw::STATUS_OK;
            log_info(__CLASS__ . "==到账成功==orderId:{$orderId}");
        } else {
            $updaInfo['status'] = Withdraw::STATUS_YZH_ERR;
        }
        $updaInfo['yzh_detail'] = json_encode([
            'status' => $dataInfo['data']['status_detail'] ?? '-1',
            'message' => $dataInfo['data']['status_message'] ?? '未知错误',
            'detail' => $dataInfo['data']['status_detail_message'] ?? '未知错误',
        ]);
        log_info(__CLASS__ . "==OrderId:{$orderId}==OrderInfo:" . json_encode($dataInfo) . "==UpdateInfo:" . json_encode($updaInfo));

        $info = Withdraw::where('yzh_order_id', $orderId)->first();
        if (empty($info)) {
            $ret = GuildWithdrawal::where('yzh_order_id', $orderId)->limit(1)->update($updaInfo);
        } else {
            $ret = Withdraw::where('yzh_order_id', $orderId)->limit(1)->update($updaInfo);
        }

        return $dataInfo;
    }

    /**
     * 参数配置对象
     */
    function createConfig()
    {
        $yzhConfig = config('yzh');
        $config = new Config();
        $config->dealer_id = $yzhConfig['dealer_id'];
        // $config->request_id = ComUtil::buildRequestId();
        $config->broker_id = $yzhConfig['broker_id'];
        // $config->mess = mt_rand(100000, 999999);
        // $config->timestamp = time();
        $config->des3_key = $yzhConfig['des3_key'];
        $config->app_key = $yzhConfig['app_key'];
        $config->private_key = $yzhConfig['private_key'];
        $config->public_key = $yzhConfig['public_key'];
        return $config;
    }
}
